import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/entity/home/task/task_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/widgets/base/wqs_button.dart';
import 'package:visibility_detector/visibility_detector.dart';
import 'package:ball_lion/server/api/king_api.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';

class TaskPage extends StatefulWidget {
  const TaskPage({super.key});

  @override
  State<TaskPage> createState() => _TaskPageState();
}

class _TaskPageState extends State<TaskPage> {
  TaskEntity? entity;

  @override
  void initState() {
    getData();
    super.initState();
  }

  Future getData() async {
    entity = await KingApi.getTask();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return VisibilityDetector(
      key: const Key("task"),
      onVisibilityChanged: (VisibilityInfo info) {
        if (!info.visibleBounds.isEmpty) {
          getData();
        }
      },
      child: Scaffold(
        appBar: Styles.appBar(
            backgroundColor: Colours.main, leadingColor: Colours.white),
        backgroundColor: Colours.scaffoldBg,
        body: Stack(
          children: [
            Positioned(
                top: 0,
                left: 0,
                right: 0,
                child: Column(
                  children: [
                    Container(
                      height: 120,
                      color: Colours.main,
                    ),
                    Container(
                      height: 60,
                      decoration: const BoxDecoration(
                          gradient: LinearGradient(
                              colors: [Colours.main, Colours.scaffoldBg],
                              begin: Alignment.topCenter,
                              end: Alignment.bottomCenter)),
                    ),
                  ],
                )),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: ListView(children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const SizedBox(height: 4),
                    point(),
                    const SizedBox(height: 16),
                    checkIn(),
                    const SizedBox(height: 10),
                    change(),
                    const SizedBox(height: 10),
                    if (entity?.list?.hasValue == true) task()
                  ],
                ),
              ]),
            ),
          ],
        ),
      ),
    );
  }

  Widget point() {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        Utils.onEvent("signin_point");
        Get.toNamed(Routes.taskPoints);
      },
      child: Container(
        width: Get.width / 2,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const QsText('我的积分', color: Colours.white, fontSize: 16),
            const SizedBox(height: 2),
            Row(
              children: [
                QsText('${entity?.points ?? 0}',
                    color: Colours.white,
                    fontSize: 20,
                    fontWeight: FontWeight.w500),
                const SizedBox(width: 8),
                Image.asset(
                  Utils.getImgPath('arrow_right.png'),
                  width: 6,
                  height: 10,
                  color: Colours.white,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget checkIn() {
    return Styles.card(
        padding: const EdgeInsets.fromLTRB(12, 12, 12, 16),
        child: Column(
          children: [
            Row(
              children: [
                QsText('连续签到${entity?.signDays ?? 0}天',
                    fontSize: 16, fontWeight: FontWeight.w500),
                const Spacer(),
                // QsText('签到提醒')
              ],
            ),
            const SizedBox(height: 16),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: List.generate(
                7,
                (index) {
                  var sign = 2;
                  if ((entity?.signDays ?? 0) >= (index + 1)) {
                    sign = 1;
                  } else if (index != 0 && index % 2 == 0) {
                    sign = 3;
                  }
                  return Column(
                    children: [
                      Image.asset(
                        Utils.getImgPath('check_in_$sign.png'),
                        width: 30,
                      ),
                      Container(height: 6),
                      QsText('${index + 1}天',
                          fontSize: 12, color: Colours.grey66)
                    ],
                  );
                },
              ),
            )
          ],
        ));
  }

  Widget change() {
    return GestureDetector(
      onTap: () async {
        Utils.onEvent('signin_point_exchange');
        var result = await Get.toNamed(Routes.pointMarket);
        if (result) getData();
      },
      child: Styles.card(
          padding: const EdgeInsets.all(12),
          child: Row(
            children: [
              Image.asset(
                Utils.getImgPath('task_duihuan.png'),
                width: 40,
              ),
              Container(width: 8),
              const Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  QsText('积分兑换', fontSize: 16, fontWeight: FontWeight.w500),
                  QsText('大额优惠等你拿', color: Colours.grey99, fontSize: 12),
                ],
              ),
              const Spacer(),
              Image.asset(
                Utils.getImgPath('arrow_right.png'),
                width: 6,
                height: 10,
              ),
            ],
          )),
    );
  }

  Widget task() {
    return Styles.card(
      padding: const EdgeInsets.all(12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          QsText('做任务赚积分', fontSize: 16, fontWeight: FontWeight.w500),
          const SizedBox(height: 8),
          ...List.generate(
            entity?.list?.length ?? 0,
            (index) => Padding(
              padding: const EdgeInsets.symmetric(vertical: 12),
              child: Row(
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      QsText(entity?.list?[index].title ?? ""),
                      QsText(entity?.list?[index].msg ?? "",
                          color: Colours.grey99, fontSize: 12),
                    ],
                  ),
                  const Spacer(),
                  QsText(entity?.list?[index].points ?? "",
                      fontSize: 13, color: Colours.goldBD5B00),
                  const SizedBox(width: 12),
                  if (entity?.list?[index].status == 1)
                    QsButton(
                      onPressed: () async {
                        var result =
                            await KingApi.receive(entity?.list?[index].type);
                        if (result == 200) {
                          getData();
                          Toast.text("领取成功");
                        }
                      },
                      backgroundColor: Colours.main,
                      foregroundColor: Colours.white,
                      width: 56,
                      height: 24,
                      borderRadius: 4,
                      textStyle: const TextStyle(fontSize: 13),
                      text: '领取',
                    ),
                  if (entity?.list?[index].status == 2)
                    QsButton(
                      onPressed: () {
                        Utils.onEvent('signin_task_go',
                            params: {"task_id": entity?.list?[index].title});
                        if (entity?.list?[index].path.hasValue == true) {
                          Utils.doJump(entity!.list![index].path!);
                        }
                      },
                      backgroundColor: Colours.white,
                      foregroundColor: Colours.main,
                      borderSide:
                          const BorderSide(color: Colours.main, width: 1),
                      width: 56,
                      height: 24,
                      borderRadius: 4,
                      textStyle: const TextStyle(fontSize: 13),
                      text: '去完成',
                    ),
                  if (entity?.list?[index].status == 3)
                    QsButton(
                      onPressed: () {},
                      backgroundColor: Colours.greyF2,
                      foregroundColor: Colours.grey99,
                      width: 56,
                      height: 24,
                      borderRadius: 4,
                      textStyle: const TextStyle(fontSize: 13),
                      text: '已完成',
                    )
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}
